package com.capgemini.scaffold.config;

import com.capgemini.scaffold.common.BusinessException;
import com.capgemini.scaffold.common.ExceptionEnum;
import com.capgemini.scaffold.dto.LoginFromDTO;
import com.capgemini.scaffold.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.capgemini.scaffold.utils.CustomConstant.USER_LOGIN_IDENTIFICATION;


/**
 * @author ShuHao.Wen
 * @since 2022/10/20
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    // 普通用户不能访问的URL
    // @Value("#{'${milestones}'.split(',')}")
    static String[] arrays = {
            "/intern/update",
            "/intern/delete",
            "/tutor/update",
            "/tutor/delete",
            "/tutor/add",
            "/intern/add",
            "/after"
    };


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取请求URL
        String requestURI = request.getRequestURI();
        // 判断是否需要拦截（ThreadLocal中是否有用户）
        LoginFromDTO user = UserHolder.getUser();

        if (user == null) {
            // 用户未登录 拦截
            throw new BusinessException(ExceptionEnum.USER_NOT_LOGIN);
        } else {

            // 判断是否是管理员 是的话直接放行
            if (user.getIdentification().equals(USER_LOGIN_IDENTIFICATION)) return true;

            // 不是管理员 判断URL是否有权限访问
            for (String array : arrays) {
                // 判断路劲是否一致 一致 没有权限 拦截
                if ((requestURI.startsWith(array))) throw new BusinessException(ExceptionEnum.USER_NOT_PERMISSION);
            }

        }
        return true;
    }

}
